//------------------------------------------------------------------------------
// Copyright (c) 2008 www.dnaide.com
// Licensed under the MIT (MIT-LICENSE.txt)
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;

namespace DNAide.Web.UI.Controls
{
	/// <summary>
	/// </summary>
	public abstract class DNAideControl: Control, IAttributeAccessor
	{
		private AttributeCollection _attributes;

		/// <summary>
		/// </summary>
		public AttributeCollection Attributes
		{
			get
			{
				if (this._attributes == null)
				{
					this._attributes = new AttributeCollection(this.ViewState);
				}
				return this._attributes;
			}
		}

		/// <summary>
		/// If the control relies on various javascript resources to run (e.g jQuery etc), 
		/// by default the controls will register the script resources.
		/// You can prevent this by setting this value to false
		/// </summary>
		public Boolean AutoRegisterScriptResources
		{
			get { return ((ViewState["AutoRegisterScriptResources"] == null) ? true : (bool)ViewState["AutoRegisterScriptResources"]); }
			set { ViewState["AutoRegisterScriptResources"] = value; }
		}

		#region IAttributeAccessor Members
		/// <summary>
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public string GetAttribute(string key)
		{
			return this.Attributes[key];
		}

		/// <summary>
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public void SetAttribute(string key, string value)
		{
			this.Attributes[key] = value;
		}

		#endregion

		/// <summary>
		/// </summary>
		/// <param name="writer"></param>
		protected override void Render(HtmlTextWriter writer)
		{
			RenderStart(writer);
			RenderAttributes(writer);
			RenderEnd(writer);
		}

		/// <summary>
		/// </summary>
		/// <param name="writer"></param>
		protected virtual void RenderStart(HtmlTextWriter writer)
		{
		}

		/// <summary>
		/// </summary>
		/// <param name="writer"></param>
		protected virtual void RenderAttributes(HtmlTextWriter writer)
		{
			if (this.ID != null)
			{
				writer.WriteAttribute("id", this.ClientID);
			}
			this.Attributes.Render(writer);
		}

		/// <summary>
		/// </summary>
		/// <param name="writer"></param>
		protected virtual void RenderEnd(HtmlTextWriter writer)
		{
		}
		
	}
}
